package main

import (
	"image"
	"image/color"
	"image/png"
	"os"
)

const (
	cellCount   = 8
	cellSize    = 100
	borderWidth = 20
	halfBorder  = borderWidth / 2
	width       = cellCount * cellSize
)

var (
	black = color.Black
	white = color.White
)

func getCellColor(x, y int) color.Color {
	if (x%2 == 0 && y%2 != 0) || (x%2 != 0 && y%2 == 0) {
		return black
	} else {
		return white
	}
}

func setCellColor(img *image.RGBA, xOffset, yOffset, x, y int) {
	img.Set(
		xOffset*cellSize+x+halfBorder,
		yOffset*cellSize+y+halfBorder,
		getCellColor(xOffset, yOffset),
	)
}

func drawCell(img *image.RGBA, xOffset, yOffset int) {
	for x := 0; x < cellSize; x++ {
		for y := 0; y < cellSize; y++ {
			setCellColor(img, xOffset, yOffset, x, y)
		}
	}
}

func fillSquare(img *image.RGBA, width int, clr color.Color) {
	for x := 0; x < width; x++ {
		for y := 0; y < width; y++ {
			img.Set(x, y, clr)
		}
	}
}

func drawBoard(img *image.RGBA) {
	for x := 0; x < cellCount; x++ {
		for y := 0; y < cellCount; y++ {
			drawCell(img, x, y)
		}
	}
}

func drawBorder(img *image.RGBA) {
	for y := 0; y < width+borderWidth; y++ {
		img.Set(0, y, black)
		img.Set(borderWidth+width, y, black)
	}

	for x := 0; x < width+borderWidth; x++ {
		img.Set(x, 0, black)
		img.Set(x, borderWidth+width, black)
	}

	for x := 0; x < width; x++ {
		img.Set(halfBorder+x, halfBorder, black)
		img.Set(halfBorder+x, halfBorder+width, black)
	}

	for y := 0; y < width; y++ {
		img.Set(halfBorder, y+halfBorder, black)
		img.Set(halfBorder+width, y+halfBorder, black)
	}
}

func saveImage(img *image.RGBA) {
	f, err := os.OpenFile("chessboard.png", os.O_WRONLY|os.O_CREATE, 0644)
	if err != nil {
		panic(err)
	}

	err = png.Encode(f, img)
	if err != nil {
		panic(err)
	}
}

func main() {
	totalWidth := width + borderWidth

	img := image.NewRGBA(image.Rect(0, 0, totalWidth+1, totalWidth+1))

	fillSquare(img, totalWidth+1, white)

	drawBoard(img)

	drawBorder(img)

	saveImage(img)
}
